package work.jame.blog.configuration.security;

import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import work.jame.blog.pojo.User;

import java.util.Collection;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * UserDetails自定义实现类
 *
 * @author Jame!
 * @date 2023/5/9 下午 9:42
 */
public class LoginUser implements UserDetails {

    //角色代码前缀
    private static final String ROLE_PREFIX = "ROLE_";

    /**
     * 当前登录用户数据
     */
    private User user;

    /**
     * 当前用户所拥有的权限码集合
     */
    private Set<String> permissions;

    @JsonIgnore
    private Set<SimpleGrantedAuthority> authorities;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (Objects.isNull(authorities)) {
            authorities = permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toSet());
        }
        return authorities;
    }


    /**
     * 添加当前用户角色代码集合
     *
     * @param roleCodes 用户拥有角色代码集合
     */
    public void addRole(Set<String> roleCodes) {
        if (!Objects.isNull(authorities)) {
            Set<SimpleGrantedAuthority> roleSimpleGrantedAuthority =
                    roleCodes.stream()
                            .map(s -> new SimpleGrantedAuthority(ROLE_PREFIX + s))
                            .collect(Collectors.toSet());
            authorities.addAll(roleSimpleGrantedAuthority);
        }
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getEmail();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return user.getStatus() == 0;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }


    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Set<String> getPermissions() {
        return permissions;
    }

    public void setPermissions(Set<String> permissions) {
        this.permissions = permissions;
    }


}
